package com.mobileClientKernel.android.serviceManager.service;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.mobileClientKernel.android.serviceManager.featureset.JJFeatureSet;
import com.mobileClientKernel.android.serviceManager.help.ReflectUtil;
import com.mobileClientKernel.android.serviceManager.network.JJRequest;
import com.mobileClientKernel.android.serviceManager.network.JJRequestError;
import com.mobileClientKernel.android.commonLayer.JJLog;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by hamilyjing on 3/31/16.
 */
public class JJService implements IJJService {

    private Integer requestFinishCount = 0;
    private Lock requestCountLock = new ReentrantLock();

    private Date recordExistBeginDate = new Date();
    private long unusedExistTimeInterval = 20 * 1000; // 20 second

    private JJFeatureSet featureSet;

    public static String serviceName() {
        return "com.mobileClientKernel.android.serviceManager.service.JJService";
    }

    public void serviceWillLoad() {
    }

    public void serviceDidLoad() {
    }

    public void serviceWillUnload() {
    }

    public void serviceDidUnload() {
    }

    public boolean needUnloading() {
        boolean need = (0 == requestFinishCount);
        if (need) {
            long timeInterval = (new Date()).getTime() - recordExistBeginDate.getTime();
            need = timeInterval > unusedExistTimeInterval;
        }

        return need;
    }

    public void actionAfterLogin(Intent intent) {

    }

    public void actionAfterLogout(Intent intent) {
    }

    public void recordRequestFinishCount(Integer count) {
        requestCountLock.lock();

        this.requestFinishCount = this.requestFinishCount + count;

        if (count > 0) {
            recordExistBeginDate = new Date();
        }

        requestCountLock.unlock();
    }

    public void callBack(final Context context, boolean success, Object object, JJRequestError error, JJRequest request) {
        requestCallBack(success, object, error, request);

        if (request.getIsNeedResponseNotification()) {
            sendBroadcast(context, success, object, error, request);
        }

        recordRequestFinishCount(1);
    }

    private void requestCallBack(boolean success, Object object, JJRequestError error, JJRequest request) {
        if (success) {
            request.getServiceCallBack().onNetworkRequestSuccess(object, request.getOtherInfo());
        } else {
            request.getServiceCallBack().onNetworkRequestFailure(error, request.getOtherInfo());
        }
    }

    private void sendBroadcast(Context context, boolean success, Object object, JJRequestError error, JJRequest request) {
        try {
            String action = request.getIdentity();
            Intent intent = new Intent(action);

            intent.putExtra("success", success);

            if (request.getResponseString() != null) {
                intent.putExtra("responseString", request.getResponseString());
            }

            Bundle bundle = new Bundle();

            if (request.getOtherInfo() != null) {
                bundle.putSerializable("otherInfo", (Serializable) request.getOtherInfo());
            }

            if (success) {
                Object model = request.currentResponseModel();
                if (model instanceof Serializable) { // todo gongjian why JJReactNativeModel can not be Serializable ? should check why?
                    bundle.putSerializable("model", (Serializable) model);
                }
            } else {
                if (error instanceof Serializable) {
                    bundle.putSerializable("model", (Serializable) error);
                }
            }

            intent.putExtras(bundle);

            context.sendBroadcast(intent);
        } catch (Exception e) {
            JJLog._e("look", e.getStackTrace()+"");
        }
    }

    public JJFeatureSet getFeatureSet() {
        if (null == featureSet) {
            featureSet = new JJFeatureSet(this);
        }
        return featureSet;
    }

    public void setFeatureSet(JJFeatureSet featureSet) {
        this.featureSet = featureSet;
    }

    public long getUnusedExistTimeInterval() {
        return unusedExistTimeInterval;
    }

    public void setUnusedExistTimeInterval(long unusedExistTimeInterval) {
        this.unusedExistTimeInterval = unusedExistTimeInterval;
    }
}
